import 'package:inmotion_protocol/lorin/bean/common/bms_info.dart';
import 'dart:typed_data';
import 'package:binary/binary.dart';
import 'package:inmotion_protocol/common/product_model.dart';
import 'package:inmotion_protocol/common/product_version.dart';
import 'package:inmotion_protocol/util/byte_util.dart';

class V18BMSAllRealTimeInfo extends BMSAllRealTimeInfo {
  V18BMSAllRealTimeInfo(ProductModel model, VersionWrapper version) : super(model, version, true) {
    generalInfo = V18BMSGeneralInfo(model, version);
    state = BMSState(model, version);
    warning = V18BMSWarning(model, version);
    protection = BMSProtection(model, version);
    error = BMSError(model, version);
  }

  @override
  V18BMSGeneralInfo get generalInfo => super.generalInfo as V18BMSGeneralInfo;

  @override
  V18BMSWarning get warning => super.warning as V18BMSWarning;
}

/// 目前仅V18Y有BMS
class V18BMSCellsVoltage extends BMSCellsVoltage {
  V18BMSCellsVoltage(super.apiVersion, super.version);

  @override
  int batteryCount() {
    return 20;
  }
}

class V18BMSGeneralInfo extends BMSGeneralInfo {
  V18BMSGeneralInfo(super.model, super.version);

  // 每个电池4个温度传感器
  @override
  int cellTempSensorCount() => 4;
}

class V18BMSWarning extends BMSWarning {
  /// 充电二极管过温告警
  Uint4 chargeDiodeOverTemp = Uint4.zero;

  /// 充电器电压错误告警
  Uint4 chargerVoltageError = Uint4.zero;

  V18BMSWarning(super.model, super.version);

  @override
  void initCompact() {
    compact = _DefaultV18BMSWarningCompact();
  }

  @override
  String toString() {
    return 'V18BMSWarning{chargeDiodeOverTemp: $chargeDiodeOverTemp, chargerVoltageError: $chargerVoltageError, ${super.toString()}}';
  }
}

class _DefaultV18BMSWarningCompact extends DefaultBMSWarningCompact<V18BMSWarning> {
  @override
  void fromBytes(V18BMSWarning output, Uint8ClampedList bytes, int offset) {
    super.fromBytes(output, bytes, offset);
    offset++;
    output.chargeDiodeOverTemp = ByteUtil.bitValue(bytes[offset], 6, 1);
    output.chargerVoltageError = ByteUtil.bitValue(bytes[offset], 7, 1);
  }
}
